"""PySide6 文本转语音示例模块

该模块演示了如何使用PySide6的QTextToSpeech类实现文本转语音功能，
包含文本输入、语音选择、音量控制等功能。
"""

import sys
from PySide6.QtCore import Qt
from PySide6.QtWidgets import (QApplication, QComboBox, QFormLayout,
    QHBoxLayout, QLineEdit, QMainWindow, QPushButton, QSlider, QWidget)

from PySide6.QtTextToSpeech import QTextToSpeech


class MainWindow(QMainWindow):
    """文本转语音主窗口类
    
    提供文本输入、语音选择、音量控制界面，并实现文本朗读功能。
    """
    
    def __init__(self):
        """初始化主窗口组件和语音引擎"""
        super().__init__()

        # 创建中央窗口部件
        centralWidget = QWidget()
        self.setCentralWidget(centralWidget)
        layout = QFormLayout(centralWidget)

        # 创建文本输入布局
        textLayout = QHBoxLayout()
        self.text = QLineEdit('Hello, PySide6')
        self.text.setClearButtonEnabled(True)
        textLayout.addWidget(self.text)
        self.sayButton = QPushButton('Say')
        textLayout.addWidget(self.sayButton)
        
        # 连接信号和槽
        self.text.returnPressed.connect(self.sayButton.animateClick)
        self.sayButton.clicked.connect(self.say)
        layout.addRow('Text:', textLayout)

        # 创建语音选择下拉框
        self.voiceCombo = QComboBox()
        layout.addRow('Voice:', self.voiceCombo)

        # 创建音量控制滑块
        self.volumeSlider = QSlider(Qt.Horizontal)
        self.volumeSlider.setMinimum(0)
        self.volumeSlider.setMaximum(100)
        self.volumeSlider.setValue(100)
        layout.addRow('Volume:', self.volumeSlider)

        # 初始化语音引擎
        self.engine = None
        engineNames = QTextToSpeech.availableEngines()
        if len(engineNames) > 0:
            engineName = engineNames[0]
            self.engine = QTextToSpeech(engineName)
            self.engine.stateChanged.connect(self.stateChanged)
            self.setWindowTitle(f'QTextToSpeech Example ({engineName})')
            self.voices = []
            
            # 添加可用语音到下拉框
            for voice in self.engine.availableVoices():
                self.voices.append(voice)
                self.voiceCombo.addItem(voice.name())
        else:
            # 如果没有可用的语音引擎，禁用朗读按钮
            self.setWindowTitle('QTextToSpeech Example (no engines available)')
            self.sayButton.setEnabled(False)

    def say(self):
        """朗读文本内容
        
        使用选定的语音和音量设置朗读输入框中的文本。
        """
        self.sayButton.setEnabled(False)
        self.engine.setVoice(self.voices[self.voiceCombo.currentIndex()])
        self.engine.setVolume(float(self.volumeSlider.value()) / 100)
        self.engine.say(self.text.text())

    def stateChanged(self, state):
        """语音引擎状态改变处理函数
        
        当语音引擎状态变为就绪时，重新启用朗读按钮。
        
        Args:
            state: 语音引擎当前状态
        """
        if (state == QTextToSpeech.State.Ready):
            self.sayButton.setEnabled(True)


if __name__ == '__main__':
    # 创建应用程序实例
    app = QApplication(sys.argv)
    
    # 创建并显示主窗口
    mainWin = MainWindow()
    mainWin.show()
    
    # 运行应用程序事件循环
    sys.exit(app.exec())